package cn.edu.ctbu.lab.api;

import cn.edu.ctbu.lab.domain.Course;
import cn.edu.ctbu.lab.helper.RUtil;
import cn.edu.ctbu.lab.service.CourseService;
import cn.edu.ctbu.lab.vo.BTPageDO;
import cn.edu.ctbu.lab.vo.CourseExt;
import cn.edu.ctbu.lab.vo.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
@Slf4j
public class CourseRestController {

    @Autowired
    private CourseService courseService;

    /**
     * 基本分页
     * @param offset
     * @param limit
     * @return
     */
    @RequestMapping(value = "/api/course/list")
    public BTPageDO<CourseExt> list(int offset, int limit){

        int pageIndex=offset/limit;

        int pageSize=limit;

        BTPageDO<CourseExt> myList=courseService.findByPage(pageIndex,pageSize);



        return  myList;

    }


    @GetMapping("/api/course/read")
    public R read(Integer id){
        Course course= courseService.findById(id).get();

        return RUtil.success(course);

    }


    @PostMapping(value = "/api/course/add")
    public R add(@Valid Course course, BindingResult bindingResult){

        if(bindingResult.hasErrors()){
            log.info(bindingResult.getFieldError().getDefaultMessage());
            return RUtil.error(-2,
                    "出错了!"+bindingResult.getFieldError().getDefaultMessage());
        }
        courseService.add(course);

        return RUtil.success();

    }


    @PutMapping(value = "/api/course/update")
    public R update(@Valid Course course, BindingResult bindingResult){

        if(bindingResult.hasErrors()){
            log.info(bindingResult.getFieldError().getDefaultMessage());
            return RUtil.error(-2,
                    "出错了!"+bindingResult.getFieldError().getDefaultMessage());
        }
        

        courseService.update(course);

        return RUtil.success();

    }


    @DeleteMapping(value = "/api/course/delete")
    public R delete(Integer[] ids){

        Integer mylen= ids.length;
        for (int i = 0; i <mylen ; i++) {

            //读取数据,再删除
            //Course item = courseService.findById(ids[i]).get();

            courseService.delete(ids[i]);


        }

        return RUtil.success();

    }



}
